﻿namespace GreenIsomer.Data.Entities.Transform {
	using System;
	using System.Collections.Generic;
	using System.Xml;
	using System.Xml.Serialization;

	[Serializable, XmlType("EdmxOutput", Namespace = Settings.Namespace)]
	public class EdmxOutput : Output, ISsdlOutput {

		[NonSerialized]
		private TypeConversionCollection typeConversions;

		public EdmxOutput() {
			typeConversions = new TypeConversionCollection();
		}

		public override string TypeDescription {
			get { return "ADO.NET Entity Data Model"; }
		}

		public override string TypeName {
			get { return "EDMX"; }
		}

		public override string DefaultFileExtension {
			get { return "edmx"; }
		}

		[XmlAttribute("Provider")]
		public string Provider { get; set; }

		[XmlAttribute("ProviderManifestToken")]
		public string ProviderManifestToken { get; set; }

		[XmlAttribute("Schema")]
		public string Schema { get; set; }

		[XmlElement("TypeConversion")]
		public TypeConversionCollection TypeConversions {
			get { return typeConversions; }
		}

		public override void Convert(Input input, string baseDirectory) {
			EdmxInput edmxInput = input as EdmxInput;
			if(edmxInput == null) {
				base.Convert(input, baseDirectory);
				return;
			}

			XmlNode schemaNode = edmxInput.SsdlNode;

			if(Provider != null)
				schemaNode.Attributes["Provider"].Value = Provider;
			if(ProviderManifestToken != null)
				schemaNode.Attributes["ProviderManifestToken"].Value = ProviderManifestToken;

			if(Schema != null) {
				XmlNodeList entitySetNodes = edmxInput.GetSsdlEntitySetNodes(schemaNode);
				if(entitySetNodes != null)
					foreach(XmlNode entitySetNode in entitySetNodes)
						entitySetNode.Attributes["Schema"].Value = Schema;
			}

			XmlNodeList propertyNodes = edmxInput.GetSsdlPropertyNodes(schemaNode);
			TypeConversion.Convert(typeConversions, propertyNodes);

			XmlAttribute gidexNamespaceAttribute = edmxInput.Document.CreateAttribute("xmlns:gidex");
			gidexNamespaceAttribute.Value = Settings.Namespace;
			schemaNode.Attributes.Append(gidexNamespaceAttribute);

			edmxInput.Document.Save(Converter.ResolvePath(baseDirectory, File));
		}

	}

}